<template>
  <nut-infinite-loading v-model="infinityValue" :has-more="hasMore" @load-more="loadMore">
    <div class="test" v-for="(item, index) in displayedSum" :key="index">{{ item.name }}</div>
  </nut-infinite-loading>
</template>
<script setup>

import { ref } from 'vue'

// 初始化数据
const displayedSum = ref([])
const sum = ref([]) // 存储所有获取的数据
const infinityValue = ref(false)
const hasMore = ref(true)
const loadedCount = ref(14) // 已加载的数据数量
const fetchCount = ref(4) // 每次加载的数量

// 模拟从后端获取数据
const fetchMoreData = (start, count) => {
  const data = [
    { name: "张三", age: 12 },
    { name: "张二", age: 13 },
    { name: "张三", age: 14 },
    { name: "张四", age: 15 },
    { name: "张五", age: 16 },
    { name: "张六", age: 17 },
    { name: "张七", age: 18 },
    { name: "张八", age: 19 },
    { name: "张九", age: 20 },
    { name: "张十", age: 20 },
    { name: "张十一", age: 20 },
    { name: "张十二", age: 20 },
    { name: "张十三", age: 20 },
    { name: "张十四", age: 20 },
    { name: "张十五", age: 20 },
    { name: "张十六", age: 20 },
    { name: "张十七", age: 20 },
    { name: "张十八", age: 20 },
    { name: "张十九", age: 20 },
    { name: "张二十", age: 20 },
    { name: "张二一", age: 20 },
    { name: "张二二", age: 20 },
    { name: "张二三", age: 20 },
    { name: "张二四", age: 20 },
    { name: "张二五", age: 20 },
    { name: "张二六", age: 20 },
    { name: "张二七", age: 20 },
    { name: "张二八", age: 20 },
    { name: "张二九", age: 20 },
    { name: "张三十", age: 20 },
  ]

  return data.slice(start,start+count)
}

// 初始化数据
const initializeData = () => {
  const initialData = fetchMoreData(0, loadedCount.value)
  sum.value = initialData
  displayedSum.value = initialData
}

initializeData()

// 加载更多数据的函数
const loadMore = (done) => {
  setTimeout(() => {
    const newData = fetchMoreData(loadedCount.value, fetchCount.value)
    if (newData.length === 0) {
      hasMore.value = false
    } else {
      sum.value = [...sum.value, ...newData]
      displayedSum.value = sum.value
      loadedCount.value += fetchCount.value
    }
    infinityValue.value = false
  }, 1000)
}
</script>

<style>
.test {
  padding: 12px 0 12px 20px;
  border-top: 1px solid #eee;
}
</style>